<template>
  <div>
    <CategorySelector></CategorySelector>
    <el-card style="margin: 20px">
      <div v-show="showList">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="addAttr"
          >添加属性</el-button
        >
        <el-table border :data="attrList">
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="150"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值列表">
            <template v-slot="{ row, $index }">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                style="margin-right: 5px"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template v-slot="{ row, $index }">
              <el-button
                @click="saveAttr(row)"
                size="mini"
                type="primary"
                style="margin-right: 5px"
                icon="el-icon-plus"
                title="修改属性"
              ></el-button>

              <el-popconfirm
                :title="`你确定要删除 ${row.attrName} 平台属性吗 ？`"
                @onConfirm="deleteAttr(row)"
              >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  title="删除属性"
                  slot="reference"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="!showList">
        <el-form :inline="true">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              size="small"
              v-model="attrForm.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="small"
          @click="addAttrValue"
          :disabled="!attrForm.attrName"
          >添加属性值</el-button
        >
        <el-button size="small" @click="cancle">取消</el-button>
        <el-table style="margin: 20px 0" :data="attrForm.attrValueList">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input
                v-model="row.valueName"
                size="mini"
                ref="InputRef"
                v-if="row.isEdit"
                @blur="toLook(row, $index)"
                @keyup.enter.native="toLook(row, $index)"
              ></el-input>
              <span
                style="display: block; width: 100%"
                v-else
                @click="toEdit(row)"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                :title="`你确定要删除${row.valueName}这个属性值吗?`"
                @onConfirm="deleteAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="mini"
                    title="删除属性值"
                    icon="el-icon-delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          style="margin-right: 10px"
          type="primary"
          size="small"
          @click="addOrUpdateAttr"
          >保存</el-button
        >
        <el-button size="small" @click="cancle">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
import { mapState } from "vuex";
import attrApi from "@/api/attr";
import { Message } from "element-ui";

export default {
  name: "",
  data() {
    return {
      attrList: [],
      showList: true,
      attrForm: {
        attrName: "", //收集属性名字
        attrValueList: [], //收集属性下面所有的属性值的数组
        categoryId: 0, //三级分类的id
        categoryLevel: 0, //分类的级别  1 2 3
      },
    };
  },
  computed: {
    ...mapState("category", ["category1Id", "category2Id", "category3Id"]),
  },
  methods: {
    // 获取平台属性列表
    async getAttrList() {
      const res = await attrApi.getAttrsList(
        this.category1Id,
        this.category2Id,
        this.category3Id
      );
      if (res.code === 200) {
        this.attrList = res.data;
      } else {
        Message({
          type: "error",
          message: "获取平台属性列表失败",
        });
      }
    },
    // 添加属性
    addAttr() {
      this.showList = false;
      // 清空上次的内容
      this.attrForm = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
    },
    // 添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        isEdit: true,
        valueName: "",
        attrId: this.attrForm.id,
      });
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.InputRef.focus();
      });
    },
    // 修改属性
    saveAttr(row) {
      this.showList = false;
      // 回显数据
      this.attrForm = cloneDeep(row);
      // 给每个属性添加isEdit
      row.attrValueList.forEach((item) => {
        this.$set(item, "isEdit", false);
      });
    },
    // 进入编辑模式
    toEdit(row) {
      // 从修改进来判断是否有这个属性
      if (Object.prototype.hasOwnProperty(row, "isEdit")) {
        row.isEdit = true; //有修改为true
      } else {
        this.$set(row, "isEdit", true); //没有添加这个属性
      }

      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.InputRef.focus();
      });
    },
    // 进入查看模式
    toLook(row, index) {
      // row是属性值对象
      if (!row.valueName.trim()) {
        this.attrForm.attrValueList.splice(index, 1);
      }
      const flag = this.attrForm.attrValueList.some((item) => {
        if (item != row) {
          return item.valueName === row.valueName;
        }
      });
      if (flag) {
        this.attrForm.attrValueList.splice(index, 1);
        Message({
          type: "error",
          message: "请不要输入重复项",
        });
      }
      row.isEdit = false;
    },
    // 删除属性值
    deleteAttrValue(index) {
      this.attrForm.attrValueList.splice(index, 1);
    },
    // 保存
    async addOrUpdateAttr() {
      // 1.获取请求参数
      // 2.整理参数  删掉属性值为空的对象  把每个属性值对象的isEdit删掉
      // 3.携带参数发送请求
      // 4.请求成功
      // 5.请求失败
      let attr = this.attrForm;

      attr.attrValueList = attr.attrValueList.filter((item) => {
        if (item.valueName.trim()) {
          //非空
          this.$delete(item, "isEdit");
          return true;
        }
      });
      if (!attr.attrValueList.length) {
        //属性值列表为空
        Message({
          message: "请确保有属性值",
          type: "error",
        });
        return;
      }

      try {
        const res = await attrApi.updateOrSaveAttr(attr);

        if (res.code === 200) {
          Message({
            type: "success",
            message: `${attr.id ? "修改" : "添加"}属性成功`,
          });
          this.showList = true;
          this.getAttrList();
        }
      } catch (error) {
        Message({
          type: "error",
          message: `${attr.id ? "修改" : "添加"}属性失败`,
        });
      }
    },
    // 删除平台属性
    async deleteAttr(row) {
      const res = await attrApi.deleteAttr(row.id);
      if (res.code === 200) {
        Message({
          type: "success",
          message: "删除平台属性成功",
        });
        this.getAttrList();
      } else {
        Message({
          type: "error",
          message: "删除平台属性失败",
        });
      }
    },
    // 取消
    cancle() {
      this.showList = true;
    },
  },
  watch: {
    category3Id: {
      handler(newVal) {
        if (!newVal) {
          this.attrList = [];
        } else {
          this.getAttrList();
        }
      },
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped></style>
